package com.will.txj.wy.security;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;

/**
 * @author: wen-yi;
 * @date: 2021/12/6 0:32;
 * @Description: 资源服务端
 */
@Configuration
@EnableResourceServer
public class ResourceConfig extends ResourceServerConfigurerAdapter {
    @Value("${app.appId}")
    private String appId;
    @Value("${app.secret}")
    private String appSecret;
    @Value("${host.uri}")
    private String domain;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Primary
    @Bean
    public RemoteTokenServices remoteTokenServices(){
        final RemoteTokenServices tokenServices = new RemoteTokenServices();
        // 设置授权服务器check_token端点完整地址
        tokenServices.setCheckTokenEndpointUrl(domain+"/oauth/check_token");
        // 设置客户端id与secret，注意client_secret值不能使用passwordEncoder加密
        tokenServices.setClientId(appId);
        tokenServices.setClientSecret(appSecret);
        return tokenServices;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 设置创建session策略
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
        // 所有请求必须授权
        http.authorizeRequests()
                //放行资源
                //.antMatchers("/app/**").permitAll()
                //其余资源需要令牌
                .anyRequest().authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        // 资源Id 类比为商户 比如：美团
        resources.resourceId("aj_server").stateless(true);
    }
}
